package com.cheng.reggie.controller;

import com.cheng.reggie.common.R;
import com.cheng.reggie.entity.Employee;
import com.cheng.reggie.entity.Page;
import com.cheng.reggie.exception.BusinessException;
import com.cheng.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired(required = false)
    private EmployeeService employeeService;

    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //1.调用Service业务方法进行用户登录,
        Employee login = employeeService.login(employee);

        //2.判断是否登录成功,成功存储到session
        if(login.getId()==1){
            session.setAttribute("employee",login.getId());
        }
        //3.返回数据
        return R.success(login);
    }

    //退出登录
    @RequestMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }

    //处理用户添加请求
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session){
        //获取登录数据中的id
        Long id = (Long) session.getAttribute("employee");

        //完善数据
        //创建人
        employee.setCreateUser(id);
        //修改人
        employee.setUpdateUser(id);

        employeeService.save(employee);

        return R.success("添加成功");
    }

    //处理分页请求
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page, Integer pageSize, String name){
        //调用service业务层方法
        Page<Employee> pageObj = employeeService.findByPage(page, pageSize, name);
        return R.success(pageObj);
    }
    //修改数据请求
    @PutMapping
    public R<String> updata(@RequestBody Employee employee, HttpSession session){
        //1.获取当前操作人的id
        Long id = (Long) session.getAttribute("employee");
        //2.完善修改人的id
        employee.setUpdateUser(id);
        //3.调用service业务层updata方法
         employeeService.updata(employee);
        return  R.success("修改成功");
    }

    //编辑数据请求
    @GetMapping("/{id}")
    public R<Employee> findById( @PathVariable Long id){
        //调用业务层通过id查询员工
        Employee employee = employeeService.findById(id);
        return  R.success(employee);
    }
}
